<template>
    <div>
        <el-card class="box-card">
            <template #header>
                <el-button type="primary" :icon="Plus" @click="addData">添加</el-button>
            </template>

            <el-table v-loading="loading" :data="tableData" style="width: 100%" border>
                <el-table-column type="index" label="序号" width="80" align="center" />
                <el-table-column prop="tmName" label="品牌名称" />
                <el-table-column label="品牌LOGO">
                    <template v-slot="{ row }">
                        <img :src="row.logoUrl" style="width:120px;">
                    </template>
                </el-table-column>
                <el-table-column label="操作">
                    <template #default="{ row }">
                        <el-button title="修改" type="warning" size="small" :icon="Edit" @click="upDate(row)"></el-button>
                        <el-button title="删除" type="danger" size="small" :icon="Delete" @click="deleteData(row)">
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination style="margin-top: 20px; text-align: center;" v-model:currentPage="currentPage"
                v-model:page-size="pageSize" :page-sizes="[3, 6, 9, 12]" :small="small" :disabled="disabled"
                :background="background" layout=" prev, pager, next, jumper,->, sizes,total" :total="total"
                @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </el-card>

        <!-- 弹出层 -->
        <el-dialog v-model="dialogVisible" :title="`${form.id ? '修改' : '添加'}品牌`" width="60%">
            <el-form :model="form" :rules="rules" ref="formRef" style="width: 80%" label-width="100px">
                <el-form-item label="品牌名称" prop="tmName" label-width="100px">
                    <el-input v-model="form.tmName" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="品牌LOGO" prop="logoUrl" label-width="100px">
                    <el-upload class="avatar-uploader" :action="`${BASE_URL}/admin/product/upload`"
                        :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                        <img v-if="form.logoUrl" :src="form.logoUrl" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                        <template #tip>
                            <div class="el-upload__tip">
                                只能上传jpg/png 文件，且不超过2M大小
                            </div>
                        </template>
                    </el-upload>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="btnTrademark">确定</el-button>
                </span>
            </template>

        </el-dialog>
    </div>
</template>

<script lang="ts">
export default {
    name: 'Trademark'
}
</script>
<!-- 
1、初步渲染页面，使用element组件库，在挂载成功之后立刻发送数据请求数据，根据返回的数据渲染页面
    分页器自带两个函数，一个是修改当前页一个是修改每页显示触发，不复杂但是需要分清每次修改的是哪个值

2、添加
    根据值判断弹出框是显示还是隐藏，用v-model绑定需要收集的数据，使用tableData绑定，根据id确定是添加还是修改


 -->

<script lang="ts" setup>
import { reactive, ref, onMounted, nextTick } from 'vue'
import { Loading, Plus, Edit, Delete } from '@element-plus/icons-vue'
import type { UploadProps, FormInstance, FormRules } from 'element-plus'
import { ElMessage, ElMessageBox } from "element-plus"
import type { TrademarkMode, TrademarkListModel } from '@/api/product/model/Trademark'

// 引入请求接口
import { reqGetTrademarkData, reqSaveTrademark, reqUpdateTrademark, reqDeleteTrademark } from '@/api/product/Trademark'

const tableData = ref<TrademarkListModel>([])

const currentPage = ref<number>(1)
const pageSize = ref<number>(6)
const total = ref<number>(10)
const small = ref(false)
const background = ref(false)
const disabled = ref(false)
const loading = ref(false)
const dialogVisible = ref(false)
// 上传图片地址：从.env.development中加载的
const BASE_URL = import.meta.env.VITE_API_URL;
const ruleFormRef = ref<FormInstance>()

// 定义函数每次调用都会清空数据
const initTrademark = () => ({ tmName: '', logoUrl: '' })
const form = reactive<TrademarkMode>(initTrademark())
// 书写校验规则
const rules = reactive<FormRules>({
    tmName: [
        { required: true, message: '品牌名称不能为空,请输入', trigger: 'blur' },
        { min: 1, max: 6, message: '品牌名称介于1--6个字符之间,请重输', trigger: 'blur' }
    ],
    logoUrl: [{ required: true, message: '请上传图片', trigger: 'change' }]
})


// 图片上传成功会执行这函数
const handleAvatarSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
    // imageUrl.value = URL.createObjectURL(uploadFile.raw!)
    // console.log(response.data);

    // 保存图片地址
    form.logoUrl = response.data

    // 清除之前的图片的校验规则
    ruleFormRef.value?.clearValidate(['logoUrl'])
}

// 图片上传可以再这里写限定的逻辑
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    const imgTypes = ['image/jpeg', 'image/jpg', 'image/png']
    if (!imgTypes.includes(rawFile.type)) {
        ElMessage.error('上传图片的格式只能是jpg/png/jepg,请重新选择')
        return false
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('图片大小不能超过2M,请重新选择...!')
        return false
    }
    return true
}

// 确定添加/修改的函数
const btnTrademark = async () => {
    if (form.id) {
        // 修改
        await reqUpdateTrademark(form)
        ElMessage({
            type: 'success',
            message: '修改品牌成功...'
        })
    } else {
        // 添加
        await reqSaveTrademark(form)
        ElMessage({
            type: 'success',
            message: '添加品牌成功...'
        })
        // 跳转到第1页
        currentPage.value = 1
    }
    dialogVisible.value = false

    getTrademarkList()
}
// 发送请求的函数
const getTrademarkList = async () => {
    loading.value = true
    const result = await reqGetTrademarkData(currentPage.value, pageSize.value)
    console.log(result.records[0]);

    loading.value = false
    tableData.value = result.records
    total.value = result.total
}

onMounted(() => {
    getTrademarkList()
})

// 点击添加出现弹出框
const addData = () => {
    // 切换页面，清空数据，清除id
    dialogVisible.value = true
    Object.assign(form, initTrademark())
    delete form.id // 清除一下id
}

// 点击修改出现弹出框
const upDate = (row: TrademarkMode) => {

    Object.assign(form, row)
    dialogVisible.value = true
    // 清除校验
    ruleFormRef.value?.clearValidate()
}


// 删除
const deleteData = (row: TrademarkMode) => {
    ElMessageBox.confirm(
        `您真的要删除${row.tmName}吗 ? `,
        'Warning',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(async () => {
            if (!row.id) return
            await reqDeleteTrademark(row.id)
            ElMessage({
                type: 'success',
                message: '删除品牌成功',
            })
            getTrademarkList()
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '删除取消',
            })
        })

}
// 更改每页显示条数触发
const handleSizeChange = (val: number) => {
    pageSize.value = val
    currentPage.value = 1
    getTrademarkList()
}
// 改变当前页触发的函数
const handleCurrentChange = (val: number) => {
    currentPage.value = val
    getTrademarkList()
}
</script>

<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>